using RabbitMQ.Client;
using System.Threading.Tasks;

namespace Beauty.Net.RabbitMQ
{
    /// <summary>
    /// RabbitMQ连接管理器
    /// </summary>
    public class RabbitMQConnectionManager : IRabbitMQConnectionManager
    {
        private readonly RabbitMQOptions _options;
        private IConnection? _connection;
        private readonly object _lock = new object();

        public RabbitMQConnectionManager(RabbitMQOptions options)
        {
            _options = options;
        }

        /// <summary>
        /// 获取或创建连接
        /// </summary>
        public IConnection GetConnection()
        {
            if (_connection == null || !_connection.IsOpen)
            {
                lock (_lock)
                {
                    if (_connection == null || !_connection.IsOpen)
                    {
                        var factory = new ConnectionFactory
                        {
                            HostName = _options.HostName,
                            Port = _options.Port,
                            UserName = _options.UserName,
                            Password = _options.Password,
                            VirtualHost = _options.VirtualHost,
                            RequestedHeartbeat = TimeSpan.FromSeconds(_options.Heartbeat),
                            RequestedConnectionTimeout = TimeSpan.FromMilliseconds(_options.ConnectionTimeout)
                        };

                        _connection = factory.CreateConnection();
                    }
                }
            }

            return _connection;
        }

        /// <summary>
        /// 创建通道
        /// </summary>
        public IModel CreateChannel()
        {
            var connection = GetConnection();
            return connection.CreateModel();
        }

        /// <summary>
        /// 关闭连接
        /// </summary>
        public void CloseConnection()
        {
            if (_connection != null && _connection.IsOpen)
            {
                _connection.Close();
                _connection.Dispose();
                _connection = null;
            }
        }
    }

    /// <summary>
    /// RabbitMQ连接管理器接口
    /// </summary>
    public interface IRabbitMQConnectionManager
    {
        IConnection GetConnection();
        IModel CreateChannel();
        void CloseConnection();
    }
}